package com.cgc.venus.server.app.service;

import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import com.cgc.venus.server.app.bean.ConfigMapBean;
import com.cgc.venus.server.app.inter.AppConfigService;
import com.cgc.venus.server.core.base.AbstractBaseService;
import com.cgc.venus.server.core.exception.VenusException;
import com.cgc.venus.server.core.k8s.inter.K8sConfigMapService;
import com.cgc.venus.server.core.utils.DateUtil;
import io.fabric8.kubernetes.api.model.ConfigMap;
import io.fabric8.kubernetes.api.model.ConfigMapList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xyr on 2017/9/20.
 */

@Service
public class AppConfigServiceImpl extends AbstractBaseService implements AppConfigService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private K8sConfigMapService k8sConfigMapService;

    /*
    * 获得所有命名空间,填充下拉框
    * */
    @Override
    public List<Map<String, Object>> getAllNamespace() throws VenusException {
        String sql = "SELECT name FROM t_namespace";
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        try {
            mapList = jdbcTemplate.queryForList(sql);
        } catch (EmptyResultDataAccessException ex) {
            return mapList;
        }
        return mapList;
    }

    /*
    * 根据用户ID,获得命名空间,填充下拉框
    * */
    @Override
    public List<Map<String, Object>> getAllNamespaceByUser(String userId) throws VenusException {
        String sql = "SELECT DISTINCT n.name FROM t_namespace n LEFT JOIN t_namespace_user nu ON n.id " +
                "= nu.namespace WHERE nu.user = ? ";
        List<Object> list = new ArrayList<Object>();
        list.add(userId);
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        try {
            mapList = jdbcTemplate.queryForList(sql,list.toArray());
        } catch (EmptyResultDataAccessException ex) {
            return mapList;
        }
        return mapList;
    }

    @Override
    public int isSuperAdmin(String userId) throws VenusException {
        String sql = "SELECT r.is_superadmin FROM t_user u  LEFT JOIN t_role r ON u.role = r.id WHERE u.id = ? ";
        List<Object> objects = new ArrayList<Object>();
        objects.add(userId);
        Map<String,Object> map = new HashMap<String, Object>();
        map =  jdbcTemplate.queryForMap(sql, objects.toArray());
        int result = 0;
        if (map.size() > 0) {
            result = (Integer) map.get("is_superadmin");
        }
        return result;
    }

    /*
    * 1: 获取配置组数据,根据命名空间
    * */
    @Override
    public List<ConfigMapBean> getConfigMap(String namespace) throws VenusException {
        List<ConfigMapBean> list = new ArrayList<ConfigMapBean>();
        ConfigMapList configMapList = k8sConfigMapService.getConfigMaps(namespace);

        if (configMapList != null) {
            List<ConfigMap> configMaps = configMapList.getItems();
            configMaps.forEach(configMap -> {
                ConfigMapBean configMapBean = new ConfigMapBean();
                configMapBean.setConfigMapName(configMap.getMetadata().getName());
                configMapBean.setNamespace(configMap.getMetadata().getNamespace());
                String createTime = configMap.getMetadata().getCreationTimestamp().replaceAll("T"," ").replaceAll("Z","");
                createTime = DateUtil.calculate(DateUtil.yyyy_MM_dd_HH_mm_ss,createTime,28800000);
                configMapBean.setCreateTime(createTime);
                Map<String,String> dataMap = configMap.getData();
                int count = 0;
                if (dataMap != null) {
                    count = dataMap.size();
                }
                configMapBean.setFileCount(count);
                list.add(configMapBean);
            });
        }
        return list;
    }

    /*
    * 2: 创建新的配置组,根据空间名称,配置组名称
    * */
    @Override
    public boolean addConfigMap(String namespace, String configMapName) throws VenusException {
        ConfigMap configMap = k8sConfigMapService.addConfigMap(namespace,configMapName);
        if (configMap != null) {
            return true;
        }
        return false;
    }

    /*
    * 3: 删除单个配置组,根据空间名,配置组名
    * */
    @Override
    public boolean deleteConfigMap(String namespace, String configMapName) throws VenusException {
        return k8sConfigMapService.deleteConfigMap(namespace,configMapName);
    }

    /*
    * 判断同一空间下是否存在相同的配置组
    * */
    @Override
    public boolean validateConfigMap(String namespace, String configMapName) throws VenusException {
        ConfigMap configMap = k8sConfigMapService.queryConfigMap(namespace,configMapName);
        if (configMap != null) {
            return true;
        }
        return false;
    }

    /*
    * 判断同一个配置组下面是否存在相同的配置文件
    * */
    @Override
    public boolean validateConfigFile(String namespace, String configMapName, String fileName) throws VenusException {
        return k8sConfigMapService.existConfigFile(namespace,configMapName,fileName);
    }

    /*
   * 5: 新增配置文件
   * */
    @Override
    public boolean addConfigFile(String namespace, String configMapName, String fileName, String fileContent) throws VenusException {
        ConfigMap configMap = k8sConfigMapService.addConfigFile(namespace,configMapName,fileName,fileContent);
        if (configMap != null) {
            return true;
        }
        return false;
    }

    /*
    * 6: 获取配置文件列表
    * */
    @Override
    public List<ConfigMapBean> getConfigFile(String namespace, String configMapName) throws VenusException {
        List<ConfigMapBean> list = new ArrayList<ConfigMapBean>();
        ConfigMap configMap = k8sConfigMapService.queryConfigMap(namespace,configMapName);
        if (configMap != null) {
            Map<String,String> dataMap = configMap.getData();
            if (dataMap != null) {
                for (Map.Entry<String,String> map : dataMap.entrySet()) {
                    String fileName = map.getKey();
                    String fileContent = map.getValue();
                    ConfigMapBean configMapBean = new ConfigMapBean();
                    configMapBean.setFileContent(fileContent);
                    configMapBean.setFileName(fileName);
                    String createTime = configMap.getMetadata().getCreationTimestamp().replaceAll("T"," ").replaceAll("Z","");
                    createTime = DateUtil.calculate(DateUtil.yyyy_MM_dd_HH_mm_ss,createTime,28800000);
                    configMapBean.setCreateTime(createTime);
                    configMapBean.setNamespace(namespace);
                    configMapBean.setConfigMapName(configMapName);
                    list.add(configMapBean);
                }
            }
        }
        return list;
    }

    /*
   * 7: 删除单个配置文件
   * */
    @Override
    public boolean deleteConfigFile(String namespace, String configMapName, String fileName) throws VenusException {
        ConfigMap configMap = k8sConfigMapService.deleteConfigFile(namespace,configMapName,fileName);
        if (configMap != null) {
            return true;
        }
        return false;
    }
}
